package com.liuweiheng.cloudpayment8004.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RabbitMQ工具类
 *
 * @author lwh
 */
public class RabbitMQUtil {

    private static ConnectionFactory factory;

    static {
        // 创建新的RabbitMQ连接工厂
        factory = new ConnectionFactory();

        // 设置RabbitMQ的 Server IP
        factory.setHost("39.107.244.108");

        // 设置RabbitMQ的 Server Port
        factory.setPort(5672);

        // 设置RabbitMQ的 Virtual Host
        factory.setVirtualHost("/ems");

        // 设置RabbitMQ的 用户名
        factory.setUsername("ems");

        // 设置RabbitMQ的密码
        factory.setPassword("123");
    }

    /**
     * 创建连接
     */
    public static Connection getConnection() {

        Connection connection = null;

        try {

            // 使用工厂创建连接
            connection = factory.newConnection();

        } catch (IOException e) {
            LogUtil.error("创建RabbitMQ连接失败");
            e.printStackTrace();
        } catch (TimeoutException e) {
            LogUtil.error("创建RabbitMQ连接超时");
            e.printStackTrace();
        }

        return connection;

    }

    /**
     * 关闭RabbitMQ连接
     * @param channel
     * @param conn
     */
    public static void closeConnection(Channel channel, Connection conn) {


        try {
            // 关闭通道连接
            if (channel != null) {
                channel.close();
            }

            // 关闭RabbitMQ连接
            if (conn != null) {
                conn.close();
            }

        } catch (IOException e) {
            LogUtil.error("关闭RabbitMQ连接失败");
            e.printStackTrace();
        } catch (TimeoutException e) {
            LogUtil.error("关闭RabbitMQ连接超时");
            e.printStackTrace();
        }
    }


}
